const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            Nation: [],
            Ducation: ducation(),
            village: [],
            cityValue: [],
            cityValue1: [],
            city: [],
            city1: [],
            personal_Image: '',
            Affiliation: [
                {
                    value: "群众",
                    label: "群众",
                },
                {
                    value: "无党派人士",
                    label: "无党派人士",
                },
                {
                    value: "民主党派成员",
                    label: "民主党派成员",
                },
                {
                    value: "共青团员",
                    label: "共青团员",
                },
                {
                    value: "中共预备党员",
                    label: "中共预备党员",
                },
                {
                    value: "中共党员",
                    label: "中共党员",
                },
            ],
        };
    },
    mounted() {
        this.getCategory();
        this.getCity();
        let ls_URL = window.location.href;
        const Personal_Resource = getQueryObject(ls_URL, "Personal_Resource");// 获取 nodeKey 参数
        if (Personal_Resource) {
            this.dataForm.Personal_Resource = Personal_Resource;
        }

    },
    watch: {
        'dataForm.ID_Card_Number'(val) {
            if (this.action != 'Add') {
                this.cityValue = [this.dataForm.RR_Province_Number, this.dataForm.RR_City_Number, this.dataForm.RR_County_Nubmer];
                this.cityValue1 = [this.dataForm.RR_Town_Number, this.dataForm.RR_Village_Number];
                if (this.dataForm.RR_County_Nubmer) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/clientOperation/getDistrictTree`,
                        type: "GET",
                        data: {
                            DistrictCode: this.dataForm.RR_County_Nubmer
                        },
                        success: (data) => {
                            this.city1 = data[0].children;
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                }
            }
        },
        personal_Image(val) {
            $.ajax({
                url: `${y}/parseIDCard`,
                type: "POST",
                data: {
                    Data: val,
                },
                success: (res) => {
                    if (res.Status == "success") {
                        this.dataForm.ID_Card_Number = res.ID_Number;
                        this.dataForm.Personal_Name = res.name;
                        this.InputID_Card_Number('230106200105091715')
                    }
                },
                dataType: "json",
            });
        }
    },
    methods: {
        ID_Validity(rule, value, callback) {
            if (!value) {
                callback(new Error('请输入身份证'));
            } else if (!ID_Validity(value)) {
                callback(new Error('身份证格式不正确'));
            } else {
                callback();
            }
        },
        PH_Validity(rule, value, callback) {
            if (!value) {
                callback(new Error('请输入联系电话'));
            } else if (!validatemobile(value)) {
                callback(new Error('联系电话格式不正确'));
            } else {
                callback();
            }
        },
        InputID_Card_Number(val) {
            if (ID_Validity(val)) {
                this.dataForm.Birthday = Return_BirthdayByID(val);
                this.dataForm.Gender = Return_SexByID(val);
                this.dataForm.Birthday = Return_BirthdayByID(val);
                // this.cityValue = [val.substring(0, 2)+'0000',val.substring(0, 4)+'00',val.substring(0, 6)]
            }
        },
        getData(nodeKey) {//查询
            const that = this;
            //获取对应子表表单对象
            let lJSONObject_Children = new Array();
            let lJSONObject_ChildData = new Object();
            try {
                //可能涉及多个子表
                document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                    let lJSONObject_ChildData_Options = new Object();
                    lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                    let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                    let ls_ChildDataForm = lJSONObject_ChildData_Options.form;

                    lJSONObject_ChildData[ls_ChildTableName] = ls_ChildDataForm;
                    lJSONObject_Children[ls_ChildTableName] = 'ChildTable';
                })
            } catch (error) { }
            //获得对应表单对象
            try {
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_TableName = lJSONObject_Data_Options.TableName;
                let ls_primary_key = lJSONObject_Data_Options.primary_key

                let lJSONObject_Data = new Object();
                lJSONObject_Data[ls_TableName] = ls_DataForm;
                lJSONObject_Data = { ...lJSONObject_Data, ...lJSONObject_ChildData };

                let lJSONObject_TableName = new Object();
                lJSONObject_TableName[ls_TableName] = 'MainTable'
                lJSONObject_TableName = { ...lJSONObject_TableName, ...lJSONObject_ChildData };
                for (let key in lJSONObject_TableName) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/generalQueryByTableName`,
                        method: "post",
                        data: {
                            Data: key,
                            Condition: `${ls_primary_key}='${nodeKey}'`,
                        },
                        success: (res) => {
                            if (lJSONObject_TableName[key] == 'MainTable') {
                                that[lJSONObject_Data[key]] = res[0];
                            } else {
                                that[lJSONObject_Data[key]] = res;
                            }
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                    });
                }
            } catch (error) { }
        },
        changeCity1(val) {
            if (val.length > 0) {
                let Town = this.city1.filter(i => i.ProvinceNumber == val[0])[0];
                let Village = Town.children.filter(i => i.ProvinceNumber == val[1])[0];
                let arr = this.dataForm.Registered_Residence.split('/');
                this.dataForm.Registered_Residence = arr[0] + '/' + arr[1] + '/' + arr[2] + '/' + Town.Province + '/' + Village.Province;
                this.dataForm.RR_Town_Number = val[0];
                this.dataForm.RR_Village_Number = val[1];
            } else {
                this.dataForm.RR_Town_Number = '';
                this.dataForm.RR_Village_Number = '';
            }
        },
        changeCity(val) {
            console.log(val);
            if (val.length > 0) {
                let Province = this.city.filter(i => i.value == val[0])[0];
                let City = Province.children.filter(i => i.value == val[1])[0];
                let County = City.children.filter(i => i.value == val[2])[0];
                this.dataForm.Registered_Residence = Province.label + '/' + City.label + '/' + County.label;
                this.dataForm.RR_Province_Number = val[0];
                this.dataForm.RR_City_Number = val[1];
                this.dataForm.RR_County_Nubmer = val[2];
                this.dataForm.RR_Town_Number = '';
                this.dataForm.RR_Village_Number = '';
                this.cityValue1 = [];
                if (val.length > 0) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/clientOperation/getDistrictTree`,
                        type: "GET",
                        data: {
                            DistrictCode: val[2]
                        },
                        success: (data) => {
                            this.city1 = data[0].children;
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                }
            } else {
                this.dataForm.Registered_Residence = '';
                this.dataForm.RR_Province_Number = '';
                this.dataForm.RR_City_Number = '';
                this.dataForm.RR_County_Nubmer = '';
                this.dataForm.RR_Town_Number = '';
                this.dataForm.RR_Village_Number = '';
                this.cityValue1 = [];
            }
        },
        getCity() {
            $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                    data.forEach(item => {
                        item.children.forEach(ite => {
                            ite.children.forEach(it => {
                                it.children = undefined
                            })
                        })
                    })
                    this.city = data;
                    if (this.action == 'Add') {
                        this.cityValue = ['230000', '232700', '232723']
                        this.changeCity(this.cityValue)
                    }

                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
        },
        getCategory() {
            $.ajax({
                url: absolutepath() + "api/Nation.json",
                type: "GET",
                success: (data) => {
                    this.Nation = data;
                },
                dataType: "json",
            });
        },
        // changeCity(val) {
        //   if (val.length > 0) {
        //     let Province = this.city.filter(i => i.value == val[0])[0];
        //     let City = Province.children.filter(i => i.value == val[1])[0];
        //     let County = City.children.filter(i => i.value == val[2])[0];
        //     let Town = County.children.filter(i => i.value == val[3])[0];
        //     this.dataForm.Registered_Residence = Province.label + City.label + County.label + Town.label;
        //     this.dataForm.RR_Province_Number = val[0];
        //     this.dataForm.RR_City_Number = val[1];
        //     this.dataForm.RR_County_Nubmer = val[2];
        //     this.dataForm.RR_Town_Number = val[3];
        //     //   $.ajax({
        //     //     url: `${mh}/generalBusiness/generalQueryByTableName`,
        //     //     type: "POST",
        //     //     data: {
        //     //         Data: 'base_system_village',
        //     //         Condition: "TownNumber = '"+val[3]+"'",
        //     //     },
        //     //     success: (data) => {
        //     //         this.village = data; // 直接使用 this
        //     //     },
        //     //     dataType: "json",
        //     // });
        //   } else {
        //     this.dataForm.Registered_Residence = '';
        //     this.dataForm.RR_Province_Number = '';
        //     this.dataForm.RR_City_Number = '';
        //     this.dataForm.RR_County_Nubmer = '';
        //     this.dataForm.RR_Town_Number = '';
        //   }
        // },
        handleChange(file, fileList) {
            const reader = new FileReader();
            reader.readAsDataURL(file.raw);
            reader.onload = () => {
                const base64Data = reader.result;
                console.log("Base64 编码的图片数据：", base64Data);
                const parts = base64Data.split("base64,");
                if (parts.length > 1) {
                    var extractedData = parts[1];
                    console.log(extractedData); //想要的数据
                } else {
                    console.log("未找到 Base64 数据");
                }
                // return
                const _this = this;
                $.ajax({
                    headers: {
                        "content-type": "application/json",
                    },
                    url: `${mh}/clientOperation/parseIDCard`,
                    method: "post",
                    data: extractedData,
                    success: (res) => {
                        console.log(res);
                        console.log(res.words_result[0].card_result);
                        _this.personal_information.ID_Card_Number =
                            res.words_result[0].card_result.公民身份号码.words;
                        _this.personal_information.Personal_Name =
                            res.words_result[0].card_result.姓名.words;
                        _this.personal_information.Gender =
                            res.words_result[0].card_result.性别.words;
                        _this.personal_information.Registered_Residence =
                            res.words_result[0].card_result.住址.words;
                        _this.personal_information.Nation =
                            res.words_result[0].card_result.民族.words;
                        const birthStr = res.words_result[0].card_result.出生.words;
                        if (birthStr.length === 8) {
                            const formattedBirthday = `${birthStr.slice(
                                0,
                                4
                            )}-${birthStr.slice(4, 6)}-${birthStr.slice(6)}`;
                            _this.personal_information.Birthday = formattedBirthday;
                        } else {
                            console.log("出生日期格式不正确，应为 8 位数字");
                        }
                    },
                    error: (err) => {
                        console.log(err);
                    },
                });
            };
            reader.onerror = () => {
                console.error("读取文件时出错");
            };
        },
        Success(res) {
            console.log(res);
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        let lJSONObject_ChildData_Options = new Object();
                        lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                        let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                        let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                        // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                        if (this[ls_DataForm][ls_primary_key]) {
                            this[ls_ChildDataForm].forEach(item => {
                                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                            })
                        }
                        //建立子表结构体
                        let JSONArray_ChildRecord = new Array();
                        JSONArray_ChildRecord = this[ls_ChildDataForm];
                        if (!this[ls_DataForm].Children) {
                            this[ls_DataForm].Children = new Object();
                        }
                        this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                    })
                } catch (error) {

                }
                // if (this[ls_DataForm].RR_County_Nubmer == '232723') {
                this[ls_DataForm].Migrant_Personal = (this[ls_DataForm].RR_County_Nubmer == '232723' ? '0' : '1')
                // }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Modify') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet['Add'] = lJSONObject_Table;
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSave",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.location.href = './personal.html'
                    } else {
                        this.$message({
                            message: '复制失败，可能原因身份证重复',
                            type: 'error'
                        })
                    }
                    this.loading = false;
                })
                // $.ajax({
                //     headers: requestHeaders(),
                //     url: `${mh}/generalBusiness/generalSave`,
                //     method: "post",
                //     data: {
                //         Data: JSON.stringify(lJSONObject_DataSet),
                //     },
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.location.href = './personal.html'
                //         } else {
                //             this.$message({
                //                 message: '复制失败，可能原因身份证重复',
                //                 type: 'error'
                //             })
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         requestPretreatment(XMLHttpRequest);
                //         this.loading = false;
                //     },
                // });
            }
        },
    },
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
